package cn.matl.servlet;

import cn.matl.pojo.Person;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionDemo1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        //得到Session
        HttpSession session = req.getSession();
        //给session中存值
        session.setAttribute("name",new Person("蕾蕾",1));
        //获取Session的ID
        String sessionId = session.getId();
        //判断Session是否已创建
        if (session.isNew()){
            resp.getWriter().write("session创建成功，ID为："+sessionId);
        }else {
            resp.getWriter().write("session在服务器中已存在，ID为："+sessionId);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
